package cn.lj.security;
import cn.hutool.json.JSONUtil;

import cn.lj.response.Result;
import cn.lj.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @file: JwtLogoutSuccessHandler
 * @version: 1.0
 * @Description: 退出数据返回JWT处理
 * 代码目的，作用，如何工作
 * @author: 李津
 * @date: 2021-05-22 15:56
 * 本代码要注意的事项、备注事项等
 */
@Component
public class JwtLogoutSuccessHandler implements LogoutSuccessHandler {

    private final JwtUtils jwtUtils;

    @Autowired
    public JwtLogoutSuccessHandler(JwtUtils jwtUtils) {
        this.jwtUtils = jwtUtils;
    }

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {

        if (authentication != null) {
            new SecurityContextLogoutHandler().logout(request, response, authentication);
        }

        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = response.getOutputStream();

        response.setHeader(jwtUtils.getHeader(), "");

        outputStream.write(JSONUtil.toJsonStr(Result.ok()).getBytes(StandardCharsets.UTF_8));

        outputStream.flush();
        outputStream.close();
    }
}
